﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CLFramework.Utility;

namespace StockMonitor.Configuration
{
    public class ETFStockPool
    {
        public static ETFStockPool Instance = new ETFStockPool();

        #region Ctor.

        private ETFStockPool()
        {
            ReLoad();
        }

        #endregion

        #region Properties

        private List<ETFPoolItem> pool = new List<ETFPoolItem>();

        public List<ETFPoolItem> Pool
        {
            get { return pool; }
            set { pool = value; }
        }

        /// <summary>
        /// 股票池文件保存路径.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:41 PM</datetime>
        /// </remarks>
        string StockPoolPath
        {
            get
            {
                return System.Windows.Forms.Application.StartupPath + System.Configuration.ConfigurationManager.AppSettings["ETFStockPool"];
            }
        }

        #endregion

        #region CRUD

        /// <summary>
        /// 重新加载股票池.
        /// 1.从本地股票池文件加载
        /// 2.调用接口查询持仓情况
        /// 3.并同步到本地股票池文件
        /// </summary>
        /// <returns>是否成功</returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:42 PM</datetime>
        /// </remarks>
        public bool ReLoad()
        {
            try
            {
                string txt = File.ReadAllText(this.StockPoolPath).Trim();
                if (txt == string.Empty)
                    pool = new List<ETFPoolItem>();
                else
                    pool = CLFramework.SerializerUtility.XmlDeserialize<List<ETFPoolItem>>(txt);

                return RefreshStockPosition();
            }
            catch (Exception e)
            {
                Log.Exception("加载股票配置失败！", e);
                return false;
            }
        }

        /// <summary>
        /// 保存股票池到文件.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:48 PM</datetime>
        /// </remarks>
        public bool Save()
        {
            try
            {
                string txt = CLFramework.SerializerUtility.XmlSerialize(pool).Trim();
                File.WriteAllText(this.StockPoolPath, txt);
                return true;
            }
            catch (Exception e)
            {
                //log
                Log.Exception("保存股票配置失败！", e);
                return false;
            }
        }

        /// <summary>
        /// 调用接口，刷新股票池中现有股票（卖出池）的持仓信息.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:44 PM</datetime>
        /// </remarks>
        public bool RefreshStockPosition()
        {
            try
            {
                //query from hs.
                var hsresult = AuthUserContext.Instance.QueryStockPosistion();

                if (hsresult == null)
                    return false;

                //update data.
                var hsdic = hsresult.ToDictionary(h => h.stock_code);
                Pool.ForEach(s =>
                {
                    if (hsdic.ContainsKey(s.StockCode))//有的才显示
                        s.CurrentAmount = Convert.ToInt32(hsdic[s.StockCode].current_amount);
                });

                return true;
            }
            catch (Exception e)
            {
                Log.Exception("更新股票持仓信息时发生错误", e);
                return false;
            }
        }

        #endregion
    }
}
